<template>
	<view class="employee-management">
		<!-- 搜索和添加区域 -->
		<view class="search-bar">
			<uni-search-bar v-model="searchKeyword" placeholder="请输入员工姓名或账号" @confirm="handleSearch"
				@clear="handleSearchClear" cancelButton="none" style="flex: 1;" />
			<button class="add-btn" @click="showAddDialog">添加员工</button>
		</view>
		<!-- 员工列表 -->
		<view class="list-container">
			<view v-for="(employee,index) in filteredEmployees" :key="employee.id" class="employee-card">
				<view class="card-left">
					<view class="card-header">
						<text class="name"><text class="no">{{index+1}}</text>{{ employee.name }}</text>
						<text class="job" :class="jobObj[employee.job]">{{ employee.job }}</text>
						<text class="status" :class="{ 'status-disabled': employee.status === 0 }" @click="toggleStatus(employee)">
							{{ employee.status === 1 ? '已启用' : '已禁用' }}
						</text>
						<view class="info-item">
							<uni-icons type="phone" size="14"></uni-icons>
							<text>{{ employee.phone }}</text>
						</view>
					</view>
					<view class="card-body">
						<view class="frist-line">
							<view class="info-item username">
								<uni-icons type="person" size="16"></uni-icons>
								<text>账号: {{ employee.username }}</text>
							</view>
							<view class="info-item">
								<uni-icons type="calendar" size="16"></uni-icons>
								<text>入职时间: {{ formatDate(employee.createTime) }}</text>
							</view>
						</view>
						<view class="info-item">
							<uni-icons type="vip" size="16"></uni-icons>
							<text>身份证: {{ formatIdNumber(employee.idNumber) }}</text>
						</view>
					</view>
				</view>
				<view class="card-right">
					<!-- 					<button class="action-btn" :disabled="employee.username==='admin'"
						:class="{ 'disable-btn': employee.status === 1, 'enable-btn': employee.status === 0 }"
						@click="toggleStatus(employee)">
						{{ employee.status === 1 ? '禁用' : '启用' }}
					</button> -->
					<button class="action-btn edit-btn" @click="showEditDialog(employee)">修改</button>
					<button class="action-btn delete-btn" :disabled="employee.username==='admin'"
						@click="confirmDelete(employee._id)">删除</button>
				</view>
			</view>

			<uni-load-more :status="loadStatus" @clickLoadMore="showMoreData"></uni-load-more>
			<view class="safe-area-box"></view>
		</view>
		<!-- 添加/编辑弹窗 -->
		<uni-popup ref="popup" type="dialog" style="z-index: 10;">
			<view class="popup-content">
				<view class="title-box">
					<text class="title-text">{{isEditMode?'修改员工':'添加员工'}}</text>
				</view>
				<view class="form-container">
					<uni-forms ref="form" :model="formData" :rules="rules">
						<uni-forms-item label="账号" name="username" label-align="right">
							<uni-easyinput v-model="formData.username" placeholder="请输入账号" :disabled="isEditMode" />
						</uni-forms-item>
						<uni-forms-item label="姓名" name="name" label-align="right">
							<uni-easyinput v-model="formData.name" placeholder="请输入姓名" />
						</uni-forms-item>
						<uni-forms-item label="手机" name="phone" label-align="right">
							<uni-easyinput v-model="formData.phone" placeholder="请输入手机号码" />
						</uni-forms-item>
						<uni-forms-item label="性别" name="sex" label-align="right">
							<view class="sex-checkbox-group">
								<checkbox-group @change="onSexChang">
									<label class="sex-checkbox">
										<checkbox value="1" :checked="formData.sex === 1" />
										<text>男</text>
									</label>
									<label class="sex-checkbox">
										<checkbox value="0" :checked="formData.sex === 0" />
										<text>女</text>
									</label>
								</checkbox-group>
							</view>
						</uni-forms-item>
						<uni-forms-item label="身份证号" name="idNumber" label-align="right">
							<uni-easyinput v-model="formData.idNumber" placeholder="请输入身份证号" />
						</uni-forms-item>
						<uni-forms-item label="职位" name="job" label-align="right">
							<uni-data-select v-model="formData.job" :localdata="jobOptions" placeholder="请选择职位" />
						</uni-forms-item>
						<uni-forms-item label="状态" name="status" label-align="right">
							<switch :checked="formData.status === 1" @change="(e) => formData.status = e.detail.value ? 1 : 0" />
						</uni-forms-item>
					</uni-forms>
					<text v-if="isEditMode" class="reset-password" @click="resetPassword">重置密码</text>
				</view>
				<view class="dialog-buttons">
					<button class="dialog-btn cancel-btn" @click="$refs.popup.close()">取消</button>
					<button class="dialog-btn confirm-btn" @click="submitForm">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		addEmployee,
		deleteEmployee,
		getEmployees,
		updateEmployee
	} from '../api/employee';
	import {
		callCloudFun
	} from '../utiles/callCloudFun';


	const jobObj = {
		'管理员': 'manager',
		'厨师': 'cook',
		'服务员': 'waiter',
		'收银员': 'cashier',
		'清洁工': 'cleaner'
	}
	// 员工数据
	const employees = ref([]);
	const searchKeyword = ref('');
	let page = 1
	let pageSize = 8
	const loadStatus = ref('more');

	// 弹窗相关
	const popup = ref(null);
	const form = ref(null);
	const isEditMode = ref(false);

	const formData = ref({});
	const resetPasswordData = {
		id: '',
		newPassword: '123456'
	}

	// 职位选项
	const jobOptions = ref([]);

	// 表单验证规则
	const rules = {
		name: {
			rules: [{
					required: true,
					errorMessage: '请输入姓名',
				},
				{
					minLength: 2,
					maxLength: 10,
					errorMessage: '姓名长度在2-10个字符之间'
				}
			]
		},
		username: {
			rules: [{
					required: true,
					errorMessage: '请输入账号'
				},
				{
					minLength: 4,
					maxLength: 16,
					errorMessage: '账号长度在4-16个字符之间'
				}
			]
		},
		phone: {
			rules: [{
					required: true,
					errorMessage: '请输入手机号码'
				},
				{
					pattern: /^1[3-9]\d{9}$/,
					errorMessage: '请输入正确的手机号码格式'
				}
			]
		},
		idNumber: {
			rules: [{
					required: true,
					errorMessage: '请输入身份证号'
				},
				{
					pattern: /^\d{17}[\dXx]$/,
					errorMessage: '身份证格式不正确'
				}
			]
		},
		job: {
			rules: [{
				required: true,
				errorMessage: '请选择职位'
			}]
		}
	};

	// 获取列表数据
	const getListData = async (page1 = 0) => {
		if (page1) {
			loadStatus.value = 'more'
			employees.value = []
			page = page1
		}
		if (loadStatus.value === 'loading') {
			return
		}
		if (loadStatus.value === 'no-more') {
			wx.showToast({
				title: '没有更多数据了...',
				icon: 'none'
			})
			return
		}
		loadStatus.value = 'loading'
		const res = await getEmployees({
			keyword: searchKeyword.value.trim(),
			page,
			pageSize
		})
		if (res && res.length > 0) {
			employees.value.splice(employees.value.length, 0, ...res.filter(e => e.username !== 'admin'))
		}
		console.log("获取数据：", employees.value);
		if (!res || res.length < pageSize) {
			loadStatus.value = 'no-more'
		} else {
			loadStatus.value = 'more'
		}
	}
	getListData()

	// 触底刷新数据
	const showMoreData = () => {
		if (loadStatus.value === 'more') {
			page++
			getListData()
		}
	}

	// 计算属性：过滤后的员工列表
	const filteredEmployees = computed(() => {
		if (!searchKeyword.value) return employees.value;
		const keyword = searchKeyword.value.trim().toLowerCase();
		return employees.value.filter(emp =>
			emp.name.toLowerCase().includes(keyword) ||
			emp.username.toLowerCase().includes(keyword)
		);
	});

	// 搜索员工
	const handleSearch = () => {
		getListData(1)
		console.log('搜索:', searchKeyword.value);
	};

	// 清空搜索
	const handleSearchClear = () => {
		searchKeyword.value = '';
		getListData(1)
	};

	const fillJobOptions = () => {
		jobOptions.value = []
		Object.keys(jobObj).forEach(item => {
			jobOptions.value.push({
				value: item,
				text: item
			})
		})
		console.log(jobOptions);
	}

	const userInfo = wx.getStorageSync('userInfo') || {}
	// 显示添加弹窗
	const showAddDialog = () => {
		fillJobOptions()
		isEditMode.value = false;
		formData.value = {
			name: '',
			username: '',
			phone: '',
			idNumber: '',
			job: '',
			status: 1,
			password: '123456',
			sex: 1,
			createUser: userInfo.empId,
			updateUser: userInfo.empId
		};
		popup.value.open();
	};

	let employeeItem = {}
	// 显示编辑弹窗
	const showEditDialog = (employee) => {
		employeeItem = employee
		fillJobOptions()
		isEditMode.value = true;
		formData.value = {
			id: employee._id,
			name: employee.name,
			phone: employee.phone,
			username: employee.username,
			idNumber: employee.idNumber,
			job: employee.job,
			status: employee.status,
			sex: employee.sex,
			updateUser: userInfo.empId
		};
		resetPasswordData.id = employee._id
		popup.value.open();
	};

	// 提交表单
	const submitForm = async () => {
		try {
			await form.value.validate();

			if (isEditMode.value) {
				// 更新员工 todo 更新数据库
				await updateEmployee(formData.value)
				employeeItem.name = formData.value.name
				employeeItem.phone = formData.value.phone
				employeeItem.username = formData.value.username
				employeeItem.idNumber = formData.value.idNumber
				employeeItem.job = formData.value.job
				employeeItem.status = formData.value.status
				employeeItem.sex = formData.value.sex
				uni.showToast({
					title: '修改成功',
					icon: 'success'
				});
			} else {
				// 添加员工
				await addEmployee(formData.value)
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
				getListData(1)
			}
			popup.value.close();
		} catch (error) {
			if (error.errMsg && error.errMsg.includes('duplicate')) {
				wx.showToast({
					title: '账号已存在',
					icon: 'error'
				})
			}
		}
	};

	// 切换员工状态
	const toggleStatus = async (employee) => {
		await updateEmployee({
			id: employee._id,
			status: employee.status === 1 ? 0 : 1
		})
		employee.status = employee.status === 1 ? 0 : 1
		uni.showToast({
			title: employee.status === 1 ? '已启用' : '已禁用',
			icon: 'success'
		});
	};

	const resetPassword = async () => {
		if (!resetPasswordData.id) {
			wx.showToast({
				title: '密码已重置，不需重复操作',
				icon: 'none'
			})
			return
		}
		const res = await wx.showModal({
			title: '提示',
			content: '你确定要把密码恢复成初始密码吗？'
		})
		if (res.cancel) {
			return
		}
		const res1 = await callCloudFun('employee', resetPasswordData)
		wx.showToast({
			title: '密码已重置'
		})
		resetPasswordData.id = ''
	}

	// 删除员工
	const confirmDelete = async (id) => {
		const res = await uni.showModal({
			title: '提示',
			content: '确定要删除该员工吗？',
		});
		if (res.cancel) {
			return
		}
		await deleteEmployee(id)
		employees.value = employees.value.filter(e => e._id !== id)
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		});
	};

	// 格式化身份证显示
	const formatIdNumber = (idNumber) => {
		if (!idNumber) return '';
		return `${idNumber.substring(0, 6)}********${idNumber.substring(14)}`;
	};

	// 格式化日期
	const formatDate = (date) => {
		if (!date) return '未知';
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	};

	const onSexChang = (e) => {
		formData.value.sex = formData.value.sex === 1 ? 0 : 1
	}

	defineExpose({
		showMoreData,
		getListData
	})
</script>

<style lang="scss" scoped>
	.employee-management {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;


	}

	.search-bar {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx 20rpx 20rpx;
		background-color: #ffffff;
		// box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
		border-bottom: 1rpx solid #eee;
		box-sizing: border-box;
		width: 100%;
		height: 150rpx;
		position: fixed;
		top: 80rpx;
		left: 0;
		z-index: 5;


		.add-btn {
			margin-left: 20rpx;
			background-color: #ff5a5f;
			color: white;
			font-weight: 700;
			font-size: 28rpx;
			height: 70rpx;
			line-height: 70rpx;
			border-radius: 8rpx;
			padding: 0 20rpx;
		}
	}

	.list-container {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
		margin-top: 225rpx;
	}

	.employee-card {
		display: flex;
		flex-direction: row;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 15rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

		.card-left {
			width: 85%;

			.card-header {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.name {
					font-size: 32rpx;
					font-weight: bold;
					margin-right: 16rpx;

					.no {
						display: inline-flex;
						font-size: 28rpx;
						width: 40rpx;
						border-radius: 25rpx;
						justify-content: center;
						align-items: center;
						color: #fa8c16;
						line-height: 100%;
					}

				}

				.job {
					font-size: 24rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					margin-right: 16rpx;

					&.manager {
						background-color: #e6f7ff;
						color: #1685a9;
					}

					&.cook {
						background-color: #fff7e6;
						color: #fa8c16;
					}

					&.waiter,
					&.cashier,
					&.cleaner {
						background-color: #f6ffed;
						color: #52c41a;
					}
				}

				.status {
					padding: 2rpx 4rpx;
					border-radius: 4rpx;
					font-size: 24rpx;
					background-color: #52c41a;
					color: #fff;

					&.status-disabled {
						background-color: #fa8c16;
						color: #fff;
					}
				}

				.info-item {
					margin-left: 15rpx;
					display: flex;
					align-items: center;
					font-size: 24rpx;
					color: #666;

					uni-icons {
						margin-right: 8rpx;
						color: #999;
					}
				}

			}

			.card-body {
				display: flex;
				flex-direction: column;
				justify-content: space-evenly;
				gap: 8rpx;

				.frist-line {
					display: flex;
					flex-direction: row;

					.username {
						width: 260rpx;
					}
				}

				.info-item {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;
					font-size: 26rpx;
					color: #666;

					uni-icons {
						margin-right: 8rpx;
						color: #999;
					}
				}
			}
		}


		.card-right {
			width: 15%;
			display: flex;
			flex-direction: column;
			justify-content: space-evenly;
			align-items: flex-end;

			.action-btn {
				margin: 4rpx 0;
				font-size: 26rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 8rpx;
				padding: 0 20rpx;

				&.edit-btn {
					background-color: #eee;
					color: #999;
				}

				&.delete-btn {
					background-color: #ff5a5f;
					color: white;
					font-weight: 700;
				}
			}
		}
	}

	.safe-area-box {
		height: env(safe-area-inset-bottom);
	}

	.popup-content {
		background-color: #fff;
		width: 80vw;
		padding: 30rpx;
		border-radius: 20rpx;

		.title-box {
			box-sizing: border-box;
			display: flex;
			width: 100%;
			justify-content: center;
			padding: 40rpx 0;

			.title-text {
				font-size: 40rpx;
				font-weight: 700;
				color: #666;
			}
		}

		.form-container {
			padding: 20rpx;
			position: relative;

			.sex-checkbox-group {
				display: flex;
				flex-direction: row;
				align-items: center;
				padding: 10rpx 0;

				.sex-checkbox {
					display: inline-flex;
					align-items: center;
					margin-right: 40rpx;

					text {
						margin-left: 8rpx;
						font-size: 28rpx
					}
				}
			}

			.reset-password {
				padding: 10rpx 15rpx;
				position: absolute;
				right: 36rpx;
				bottom: 75rpx;
				background-color: red;
				color: #fff;
				font-size: 28rpx;
				border-radius: 40rpx;
			}
		}

		.dialog-buttons {
			display: flex;
			justify-content: space-between;
			margin-top: 40rpx;

			.dialog-btn {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				font-size: 28rpx;

				&.cancel-btn {
					background-color: #eee;
					color: #999;
					margin-right: 20rpx;
				}

				&.confirm-btn {
					background-color: #ff5a5f;
					color: white;
					font-weight: 700;
				}
			}
		}
	}
</style>